#!/usr/bin/env python
# encoding: utf-8
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.core import serializers
from django.utils.html import escape
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.contrib.sessions.models import Session
from django.utils.encoding import smart_str
import base64
import settings
import os
from eim.utils import *
import urllib
from PIL import Image

def proc_createThumbnail( srcpath, dstpath ):
    if not os.path.isfile( srcpath ):
        return
    # mkdir -p dirname(dstpath)
    dir = os.path.dirname( dstpath )
    mkdirx( dir )
    # make thumbnail
    thumbnail_size = (150, 100)
    img = Image.open( srcpath )
    if img.mode not in ( "L", "RGB" ):
        img = img.convert( "RGB" )
    img.thumbnail( thumbnail_size, Image.ANTIALIAS )
    img.save( dstpath )
    
def img_getThumbnail( request ):
    fpath = request.GET["fpath"]
    fpath = base64.urlsafe_b64decode( fpath.encode("utf-8") )
    
    srcpath = settings.FILES_ROOT + "/" + fpath
    srcpath = srcpath.replace( "//", "/" )
    dstpath = settings.THUMBNAILS_ROOT + "/" + fpath
    dstpath = dstpath.replace( "//", "/" )
    
    if not os.path.isfile( dstpath ):
        # create thumbnail here
        proc_createThumbnail( srcpath, dstpath )
        
    ext = os.path.splitext( dstpath )[1][1:]
    mimetype="image/"+ext

    f=open(dstpath,"rb")
    html=f.read()
    f.close()
    return HttpResponse( html, mimetype=mimetype )

@login_required
def xml_subFolders( request ):
    currpath = ""
    if request.POST.has_key( "node" ):
        currpath = request.POST["node"]
    if not currpath:
        currpath = "Lw=="
    currpath = base64.urlsafe_b64decode( currpath.encode("utf-8") )
    abspath = settings.FILES_ROOT + currpath

    subfolders = []
    for path in os.listdir( abspath ):
        if os.path.isdir( abspath+"/"+path ):
            nowpath = currpath+"/"+path
            nowpath = nowpath.replace( "//", "/" )
            node = {}
            node["text"] = path.decode("gb18030")
            node["id"] = base64.urlsafe_b64encode( nowpath ).strip()
            node["cls"] = "folder"
            subfolders.append( node )
    content = str( subfolders )
    content = content.replace( " u'", "'")
    return HttpResponse( content, mimetype="application/javascript" )

@login_required
def action_createSubFolder( request ):
    # 没有指定参数，返回失败
    if not request.POST.has_key("fpath") or not request.POST.has_key("newFolder"):
        return HttpResponseBadRequest( "未指定正确的参数" )
    
    fpath = request.POST["fpath"]
    fpath = base64.urlsafe_b64decode( fpath.encode("utf-8") )
    newFolder = request.POST["newFolder"].encode("gb18030")
    absfpath = settings.FILES_ROOT + fpath
    # 指定的父结点不存在，或不是文件夹
    if not os.path.isdir( absfpath ):
        return HttpResponseBadRequest( "该区域不能建立文件夹" )
    absNewFolder = absfpath + "/" + newFolder
    # 有同名文件已经存在，无法建立新文件夹
    if os.path.isfile( absNewFolder ):
        return HttpResponseBadRequest( "有同名文件存在，无法建立新文件夹" )
    if os.path.isdir( absNewFolder ):
        return HttpResponseBadRequest( "文件夹已经存在" );
    os.makedirs( absNewFolder, mode = 0775 );
    return HttpResponse( "成功建立新文件夹" );

@login_required
def action_renameFolder( request ):
    # 没有指定参数，返回失败
    if not request.GET.has_key("fpath") or not request.GET.has_key("newName"):
        return HttpResponseBadRequest( "未指定正确的参数" )
    fpath = request.GET["fpath"]
    fpath = base64.urlsafe_b64decode( fpath.encode("utf-8") )
    abspath = settings.FILES_ROOT + fpath
    abspath = abspath.replace( "//", "/" )
    newName = request.GET["newName"].encode("gb18030")
    # 指定的结点不存在
    if not os.path.isdir( abspath ):
        return HttpResponseBadRequest( "指定的文件夹不存在，重命名失败。" )
    # 新文件夹已经存在
    newpath = os.path.dirname( abspath ) + "/" + newName
    if os.path.exists( newpath ):
        return HttpResponseBadRequest( "新文件夹名称已经被使用，重命名失败。" )
    try:
        os.rename( abspath, newpath )
    except:
        return HttpResponseBadRequest( "系统错误，重命名失败。\r\n请再重新操作，如果多次操作还不正确，请与系统管理员联系。")
    return HttpResponse( "目录重命名成功！" )

@login_required
def action_deleteFolder( request ):
    if not request.POST.has_key("fpath"):
        return HttpResponseBadRequest( "未指定正确的参数" )
    fpath = request.POST["fpath"]
    fpath = base64.urlsafe_b64decode( fpath.encode("utf-8") )
    abspath = settings.FILES_ROOT + fpath
    abspath = abspath.replace( "//", "/" )
    if not os.path.isdir( abspath ):
        return HttpResponseBadRequest( "指定的文件夹不存在。" )
    rmdirx( abspath )
    return HttpResponse( "删除目录成功！" )


def AuthCheckPassed( sessionid ):
    obj = Session.objects.get( session_key = sessionid );
    if obj:
        return True
    return False

def action_imageUpload( request ):
    # 做最简单的验证
    # 只要sessionid存在，则通过
    if not AuthCheckPassed( request.POST["sessionid"] ):
        return HttpResponseBadRequest( "要求身份验证" )
    
    if request.method != "POST":
        return HttpResponseBadRequest( "未指定正确的参数" )

    fpath = request.POST["fpath"]
    fpath = base64.urlsafe_b64decode( fpath.encode("utf-8") )
    abspath = settings.FILES_ROOT + fpath
    abspath = abspath.replace( "//", "/" )
    fname = request.POST["Filename"]

    dstpath = abspath + "/" + fname.encode("gb18030")
    dstpath = dstpath.replace( "//", "/" )
    fWriter = open( dstpath, "wb" )
   
    fobj = request.FILES["Filedata"]
    for data in fobj.chunks():
        fWriter.write(data)
    fWriter.close()
    
    return HttpResponse( "上传成功！" )

@login_required
def xml_getImages( request ):
    currpath = ""
    if request.method == "POST":
        if request.POST.has_key("currpath"):
            currpath = request.POST["currpath"]
            currpath = base64.urlsafe_b64decode( currpath.encode("utf-8") )
    if not currpath:
        currpath = "/"
    abspath = settings.FILES_ROOT + currpath

    imgs = []
    for file in os.listdir( abspath ):
        if os.path.isfile( abspath + "/" + file ):
            ext = os.path.splitext( file )[1].lower()
            if ext in [".jpg", ".gif", ".bmp", ".jpeg", ".png"]:
                thumbnail_url  = settings.THUMBNAILS_URL_PREFIX + "?fpath="
                thumbnail_url += base64.urlsafe_b64encode( currpath + "/" + file ).strip().replace( "\n", "" )
                thumbnail_url = thumbnail_url.replace( "//", "/" )
                
                ori_url = settings.FILES_URL_PREFIX + currpath + "/" + file
                ori_url = ori_url.replace( "//", "/" )
                
                filename = ""
                len = 18
                while len > 1:
                    try:
                        filename = file[:len].decode("gb18030")
                        break
                    except:
                        len -= 1
                    
                imgs.append({
                    "name": filename,
                    "ori_url": urllib.pathname2url( ori_url ),
                    "thumbnail_url": thumbnail_url,
                })
    contentObj = {}
    contentObj["images"] = imgs
    content = str( contentObj )
    content = content.replace( " u'", "'" )
    return HttpResponse( content, mimetype="application/javascript" )

def view_login( request ):
    username = request.POST["loginUsername"]
    password = request.POST["loginPassword"]
    
    user = authenticate( username = username, password = password )
    if user is not None:
        if user.is_active:
            login( request, user )
            return HttpResponse( "{ success: true}", mimetype="application/javascript" )
        else:
            return HttpResponse( "{ success: false, errors: { reason: '帐号被锁定...' }}", mimetype="application/javascript" )
    else:
        return HttpResponse( "{ success: false, errors: { reason: '错误的用户名或密码...' }}", mimetype="application/javascript" )